package com.guo.core.framework.chain;

import com.guo.core.framework.chain.post.Post;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * 执行链
 * @param <Req> 执行链请求参数
 * @param <Rsp> 执行链响应参数
 */
public class PostChain<Req, Rsp> implements Chain<Post<Req,Rsp>, PostChain<Req, Rsp>>{

    private final List<Post<Req,Rsp>> chain = new ArrayList<>();

    @Override
    public PostChain<Req, Rsp> addChain(Post<Req, Rsp> element) {
        chain.add(element);
        return this;
    }

    /**
     * 执行
     * @param req 节点逻辑入参
     * @param rsp 节点逻辑响应
     * @return rsp
     */
    public Rsp post(Req req, Rsp rsp) {
        Assert.notEmpty(chain, "执行链不能为空。");

        for (int i = 0; i < chain.size(); i++) {
            Post<Req,Rsp> current = chain.get(i);
            if (i == 0) {
                current.post(req, rsp);
                continue;
            }

            Post<Req,Rsp> pre = chain.get(i-1);
            if (pre.getDoNext()) {
                current.post(req, rsp);
                continue;
            }
        }

        return rsp;
    }

}
